import { messages } from "share/common";
import React from 'react'
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import { Button, Badge, Popover, Modal, message } from 'antd'
import ResizeTable from 'components/resize-table'
import 'styles/expense-reimbursement-control/reimbursement/reimbursement.scss'
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import errorMessage from 'share/errorMessage'

class Reimbursement extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      columns: [
        {title: messages("common.sequence"/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) =>
          index + 1 + this.state.pageSize * this.state.page},
        {title: messages('expense-reimbursement-control.key18')/*规则编码*/, dataIndex: 'code', width: 120},
        {title: messages('expense-reimbursement-control.key31')/*规则名称*/, dataIndex: 'name', render: value => <Popover content={value}>{value}</Popover>},
        {title: messages('common.expense.type')/*费用类型*/, dataIndex: 'expenseTypes', render: value => {
          let showExpense = [];
          (value || []).map(item => showExpense.push(item.name));
          return (
            <Popover placement="topLeft"
                     overlayStyle={{maxWidth:500}}
                     content={showExpense.join('、')}>{showExpense.join('、')}</Popover>
          )
        }},
        {title: messages('expense-reimbursement-control.key29')/*适用人员*/, dataIndex: 'userGroups', render: value => {
          let showUser = [];
          (value || []).map(item => showUser.push(item.name));
          return showUser.length ? (
            <Popover placement="topLeft"
                     overlayStyle={{maxWidth:500}}
                     content={showUser.join('、')}>{showUser.join('、')}</Popover>
          ) : messages('expense-reimbursement-control.key28')/*通用*/
        }},
        {title: messages('expense-reimbursement-control.key32')/*分配公司*/, dataIndex: 'companys', render: value => {
          let showCompany = [];
          (value || []).map(item => showCompany.push(item.name));
          return showCompany.length ? (
            <Popover placement="topLeft"
                     overlayStyle={{maxWidth:500}}
                     content={showCompany.join('、')}>{showCompany.join('、')}</Popover>
          ) : messages('expense-reimbursement-control.key28')/*通用*/
        }},
        {title: messages('expense-reimbursement-control.key33')/*控制方式*/, dataIndex: 'controlType', width: 100, render: value => (
          value === 'DAY' ? messages('expense-reimbursement-control.key34')/*每天*/ :
            (value === 'MONTH' ? messages('expense-reimbursement-control.key35')/*每月*/ :
              (value === 'QUARTER' ? messages('expense-reimbursement-control.key36')/*每季度*/ : messages('expense-reimbursement-control.key37')/*汇总校验*/))
        )},
        {title: messages('common.column.status'/*状态*/), dataIndex: 'status', width: 80, render: value => (
          <Badge status={value ? 'success' : 'error'}
                 text={value ? messages("common.status.enable") : messages("common.status.disable")}/>
        )},
        {title: messages('expense-reimbursement-control.key38')/*创建来源*/, dataIndex: 'source', width: 100, render: value =>
          Number(value) === 1001 ? messages('expense-reimbursement-control.key39')/*帐套级*/ : messages('expense-reimbursement-control.key40')/*公司级*/},
        {title: messages('common.operation'/*操作*/), dataIndex: 'ruleOID', width: 120, render: (value, record) => (
          record.source === 1001 && !props.tenantMode ? <a>{messages('common.view')/*查看*/}</a> : (
            <div className="operate-column">
              <a>{messages('common.edit')/*编辑*/}</a>
              <a className="delete" onClick={e => this.deleteRule(e, value)}>{messages('common.delete')/*删除*/}</a>
            </div>
          )
        )}
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {total: 0},
      setOfBooksId: props.nowSetOfBooks.id,
    }
  }

  componentDidMount() {
    this.getList()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.nowSetOfBooks.id !== this.state.setOfBooksId) {
      this.setState({ setOfBooksId: nextProps.nowSetOfBooks.id }, () => {
        this.getList()
      })
    }
  }

  getList = () => {
    const { tenantMode } = this.props;
    const { page, pageSize, setOfBooksId } = this.state;
    let params = { page, size: pageSize, businessType: 1001 };
    tenantMode && (params.setOfBooksId = setOfBooksId);
    this.setState({ loading: true });
    reimburseService.getRuleList(params).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count'] || 0),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ loading: false })
    })
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
    }
  };

  //新建规则
  newRule = () => {
    let newRuleUrl = menuRoute.getRouteItem('reimbursement-new-rule').url;
    this.context.router.push(newRuleUrl.replace(':setOfBooksId', this.props.nowSetOfBooks.id))
  };

  //删除规则
  deleteRule = (e, ruleOID) => {
    e.stopPropagation();
    Modal.confirm({
      title: messages('expense-reimbursement-control.key41')/*确认删除？*/,
      content: messages('expense-reimbursement-control.key42')/*分配的公司将不可用该规则，你还要继续吗？*/,
      onOk: () => {
        this.setState({ loading: true });
        reimburseService.deleteRule(ruleOID).then(() => {
          this.getList();
          message.success(messages('common.delete.success', {name: ""})/*删除成功*/)
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ loading: false })
        })
      },
    })
  };

  handleRowClick = (record) => {
    let ruleDetailUrl = menuRoute.getRouteItem('reimbursement-rule-detail').url;
    this.context.router.replace(ruleDetailUrl.replace(':setOfBooksId', this.props.nowSetOfBooks.id).replace(':ruleOID', record.ruleOID));
  };

  render() {
    const { loading, columns, data, pagination } = this.state;
    return (
      <div className="reimbursement">
        <Button type="primary"
                icon="plus"
                className="new-rule-btn"
                onClick={this.newRule}
        >{messages('expense-reimbursement-control.key43')/*新建规则*/}</Button>
        <ResizeTable
          rowKey="ruleOID"
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          bordered
          size="middle"
        />
      </div>
    )
  }
}

Reimbursement.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(Reimbursement)
